/**
 * Created by liuqiang on 2019/12/30
 *
 * 数据请求统一封装
 */

//导入模块
import md5 from 'md5'
import sha1 from 'sha1'
import Ls from '@/utils/storage'
import qs from 'qs'
import getApiParam from './getApiParam'
import { apiparent, baonahao } from './env'


/**
 * 拼接keys和data参数
 * @param {*} params_key
 * @param {*} params_val
 */
function _object(params_key, params_val, base_url, keys) {
  var oApiParam = getApiParam.getApiParam(base_url);
  let sPackey = oApiParam["packey"];
  let sSecurity = oApiParam["security_code"];
  let _obj = {
    'keys[packey]': sPackey,
    'keys[security_code]': sSecurity,
    'keys[data_type]': 'json',
    'keys[token_key]': Ls.getItem("token_keys"),
    'keys[token_val]': Ls.getItem("token_vals"),
  }
  params_key.forEach((v, i) => _obj[v] = params_val[i])
  _obj['keys[data_sign]'] = _setDataSign(keys, sSecurity)
  return _obj;
}


/**
 * 签名算法
 * @param {*} params
 * @param {*} code
 */
 function _setDataSign(params, code) {
  params = params.data || params
  for(let k in params) {
    if(Object.prototype.toString.call(params[k]) === '[object Object]') {
      _setDataSign(params[k], code)
    } else if(Object.prototype.toString.call(params[k]) === '[object Array]') {
      for (let i = 0; i < params[k].length; i++) {
        _setDataSign(params[k][i], code)
      }
    } else if(params[k] === '' || params[k] === undefined || params[k] === null) {
      delete params[k]
    } else if (typeof params[k] === 'number') {
      params[k] = params[k].toString()
    } else {
      params[k] = params[k]
    }
  }
  let $param_str = JSON.stringify(params)
  if ($param_str == '{}') {
    $param_str += code
  } else {
    $param_str+=code
  }
  let $sign = md5($param_str);
  $sign = sha1($sign);
  $sign = md5($sign);
  $sign = sha1($sign);
  $sign = $sign.substr(4, 32);
  return $sign;
 }


/**
 * 获取参数
 * @param {*} params
 */
function _getParams(params) {
  let params_key = [],
    params_val = []
  for (let k1 in params) {
    let params1 = params[k1]
    for (let k2 in params1) {
      let params2 = params1[k2]
      if (typeof params2 === 'object') {
        for (let k3 in params2) {
          let params3 = params2[k3]
          if (params3) {
            params_key.push(`${k1}[${k2}][${k3}]`)
            params_val.push(params3)
          }
        }
      } else {
        // if (params2) {
          params_key.push(`${k1}[${k2}]`)
          params_val.push(params2)
        // }
      }
    }
  }
  return {
    params_key,
    params_val,
  }
}

export default function fetch(options) {
  return new Promise((resolve, reject) => {
    // wx.showLoading();
    //处理请求接口
    if(!options.baseURL){
      options.baseURL = apiparent
    }
    wx.request({
      url: `${options.baseURL}${options.url}`,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: _object(_getParams(options.params).params_key, _getParams(options.params).params_val, options.baseURL, options.params),
      success (res) {
        if(!res.data.status){
          wx.showToast({
            title: res.data.code_user_msg || res.data.code_msg || "出错啦",
            icon: 'none',
            duration: 1500
          })
          reject(res.data)
          return
        }
        resolve(res.data)
      },
      fail: function(error) {
        wx.showToast({
          title: '操作失败！' + error.errMsg,
          icon: 'none',
          duration: 1500
        })
        reject(error)
      },
      complete: function() {
        // wx.hideLoading();
      }
    })
  })
}
